package com.web;

import com.spring.BeanPostProcessor;
import com.spring.annotation.AutoWired;
import com.spring.annotation.Component;
import com.spring.annotation.PostConstruct;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.bridge.SLF4JBridgeHandler;

import java.io.File;
import java.io.IOException;
import java.util.logging.LogManager;

/**
 * @author chengjy
 * @date 2025/4/15
 */
@Component
public class WebServer {

    @AutoWired
    private DispatcherServlet dispatcherServlet;

    @PostConstruct
    public void start() throws LifecycleException {
        LogManager.getLogManager().reset();
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();

        int port = 8080;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.getConnector();

        String contextPath = "";
        String docBase = new File(".").getAbsolutePath();
        Context context = tomcat.addWebapp(contextPath, docBase);

        tomcat.addServlet(contextPath, "dispatcher", dispatcherServlet);

        context.addServletMappingDecoded("/*", "dispatcher");
        tomcat.start();
        System.out.println("web server start");
    }

}
